﻿using System;
using System.Linq;
using Fee.Orders;
using Fee.Stores;
using Identity;

namespace Fee.VendorMatchers
{
    public class VendorMatcher
    {
        public VendorMatcher(ContractType contractType)
        {
            ContractType = contractType;
        }

        public VendorMatcher()
        {

        }

        public District District { get; set; }

        /// <summary>
        /// </summary>
        /// <remarks>
        ///     委托单位类型：设计与监理单位：不分专业，只分区域
        ///     施工单位：驻地网：专线（含WLAN管线部分）和集家客预覆盖是一样
        ///     WLAN和室分是一样
        ///     专线有一个重客和普客的区分（目前是由人工判断是否为重客？），重客的设计和监理单位与客户实际区域的对应单位一致，但施工单位不跟随区域变化，指定为虹信。
        /// </remarks>
        public ConstructionType ConstructionType { get; set; }

        public int Id { get; set; }
        public int Year { get; set; }

        /// <summary>
        /// </summary>
        public Vendor Vendor { get; set; }

        public ContractType ContractType { get; set; }

        public bool TryMatch<T>(ContractType contractType, Station station, ConstructionType constructionType,
            IFrameworkContractStore<T> contractStore, int signYear,
            out DelegateOrderDetail delegateOrderDetail)
            where T : FeeDbContext
        {
            delegateOrderDetail = null;

            var result = IsMatch(contractType, station, constructionType, signYear);

            if (result)
                delegateOrderDetail = CreateIt(contractStore);
            return result;
        }

        protected bool IsMatch(ContractType contractType, Station station,
            ConstructionType constructionType, int effectYear)
        {
            if (contractType != ContractType)
                return false;
            if (ConstructionType != constructionType)
                return false;

            if (effectYear != Year)
                return false;
            if (!IsMatchStation(station))
                return false;
            return true;
        }

        protected virtual bool IsMatchStation(Station station)
        {
            return station.OrderDistrict.Id == District.Id;
        }


        private DelegateOrderDetail CreateIt<T>(IFrameworkContractStore<T> frameworkContract)
            where T : FeeDbContext
        {
            var framework = frameworkContract.FindContractsByVendor(Vendor.Id, DateTimeOffset.Now);
            return new DelegateOrderDetail
            {
                ConstructionType = ConstructionType,
                ContractType = ContractType,
                Contract = framework.FirstOrDefault(),
                Operator = ConstructionOperator.Added,
             
            };
        }
    }
}